# -*- coding: utf-8 -*-            
# @Author : HJH
# @Time : 2024/6/1 17:37
# @Use :
import datetime
import hashlib
import json
import time

import requests
from loguru import logger


def send_wechat_msg(text):
    headers = {
        "Content-Type": "application/json"
    }

    url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send"

    params = {
        "key": "82d2eba8-167a-4be8-bbc8-388bbebe09fe"
    }

    data = {
        "msgtype": "text",
        "text": {
            "content": text,
            "mentioned_list": ["@all"],
        }
    }

    response = requests.post(url, headers=headers, params=params, data=json.dumps(data))

    print(response.text)
    print(response)


def get_date_time(datetime_str):
    # 输入日期时间字符串
    # datetime_str = "2024-02-15 21:15:00"

    # 将日期时间字符串转换为datetime对象
    datetime_obj = datetime.datetime.strptime(datetime_str, "%Y-%m-%d %H:%M")

    # 获取当前时区的时间戳
    timestamp = datetime_obj.timestamp()

    # 将时间戳转换为整数
    timestamp = int(timestamp)

    # 在时间戳后面添加3个零，使其长度为13位
    return str(timestamp) + "000"


def send_extra(path: str, body: dict):
    appkey = "B20230907024"
    secret = "NoPt5JpRfRU6d4pR75Mz8nWdLQafhGbR"
    url = "http://openapi.tenfli.com/extra/"

    # 签名生成
    time_millis = int(time.time() * 1000)
    text = f"{appkey}&{time_millis}&{secret}"
    sign = hashlib.md5(text.encode('utf-8')).hexdigest()

    # 构建请求
    headers = {
        "Content-Type": "application/json",
        "appKey": appkey,
        "sign": sign,
        "timestamp": str(time_millis)
    }

    """
    请求接口
    """
    max_tries = 5  # 最大尝试次数
    num_tries = 0  # 已尝试次数
    sleep_time = 3  # 设置等待时间
    result = ''
    while num_tries < max_tries:
        try:
            response = requests.post(url + path, headers=headers, json=body)
            result = response.text
            return json.loads(result)
        except (requests.exceptions.RequestException, json.JSONDecodeError) as e:
            logger.error(f"【腾鸢{path}请求】结果: {str(result)}")
            num_tries += 1
            if num_tries >= max_tries:
                # 如果已经尝试到最大次数，跳出循环，放弃重试
                logger.error(f"重试{max_tries}次后仍然失败，放弃重试。")
                break
            # 打印日志，并且睡眠
            logger.info(f"请求失败，休眠 {sleep_time} 秒后进行第 {num_tries + 1} 次尝试。")
            logger.error(e)
            time.sleep(sleep_time)


def send_api(path: str, body: dict):
    appkey = "B20230907024"
    secret = "NoPt5JpRfRU6d4pR75Mz8nWdLQafhGbR"
    url = f"http://openapi.tenfli.com/api/{path}"

    # 签名生成
    time_millis = int(time.time() * 1000)
    text = f"{appkey}&{time_millis}&{secret}"
    sign = hashlib.md5(text.encode('utf-8')).hexdigest()

    # 构建请求
    headers = {
        "Content-Type": "application/json",
        "appKey": appkey,
        "sign": sign,
        "timestamp": str(time_millis)
    }

    """
    请求接口
    """
    max_tries = 5  # 最大尝试次数
    num_tries = 0  # 已尝试次数
    sleep_time2 = 3  # 设置等待时间
    result = ''
    while num_tries < max_tries:
        try:
            response = requests.post(url, headers=headers, json=body)
            result = response.text
            res_data = json.loads(result)
            # print(json.dumps(res_data))

            if res_data['content'] is not None and len(res_data['content']) > 0:
                return res_data['content']
            else:
                logger.error(f"【腾鸢报价接口】结果: {str(res_data)}")
                return None
        except (requests.exceptions.RequestException, json.JSONDecodeError) as e:
            logger.error(f"【腾鸢报价接口】结果: {str(result)}")
            num_tries += 1
            if num_tries >= max_tries:
                # 如果已经尝试到最大次数，跳出循环，放弃重试
                logger.error(f"重试{max_tries}次后仍然失败，放弃重试。")
                break
            # 打印日志，并且睡眠c
            logger.info(f"请求失败，休眠 {sleep_time2} 秒后进行第 {num_tries + 1} 次尝试。")
            logger.error(e)
            time.sleep(sleep_time2)


def order_policies(flight_no, dep, arr, dep_time, arr_time):
    dep_time = get_date_time(dep_time)
    arr_time = get_date_time(arr_time)
    req = {
        "accounts":
            [
                {
                    "supplierCode": "OFFICIAL_APP",
                    "username": "394379253089",
                    "password": "070122"  # 支付密码：789369
                }
            ],
        "keepNotMatched": True,
        "crawlOnly": True,
        "otaOrderNo": "O3N7GFX1W10GQS008696",
        "tickets":
            [
                {
                    "arr": arr,
                    "arrTime": arr_time,
                    "birthDay": "1996-01-10",
                    "buildPrice": 0,
                    "cabinCode": "W",
                    "certCode": "410185200201189869",
                    "certType": "ID",
                    "dep": dep,
                    "depTime": dep_time,
                    "flightNo": flight_no,
                    "fuelPrice": 0,
                    "gender": "FEMALE",
                    "mobile": "13783590698",
                    "name": "赵瑞凯",
                    "printPrice": 0,
                    "salePrice": 0,
                    "type": "ADU"
                }
            ]
    }

    return send_api('order/policies', req)


def check_price(order_no, flight_no, dep, arr, cabin, dep_time, arr_time):
    """
    检查价格是否放出来
    :return:
    """
    count = 0

    while count < 360:
        # 发送请求获取报价数据
        res_datas = order_policies(flight_no, dep, arr, dep_time, arr_time)

        policy_types = ['特价经济舱 [优惠券]', '经济舱 [优惠券]', '折扣经济舱 [优惠券]', '优选经济舱 [优惠券]',
                        '折扣公务舱 [优惠券]']
        datas = [data for data in res_datas if data['cabinCode'] == cabin and data['policyTypeDesc'] in policy_types]
        if len(datas) > 0:
            send_wechat_msg(f"{order_no} 已找到合适报价!!!")
            return None

        # 每次循环更新计数
        count += 1
        print(f"{order_no}未找到合适报价 {count}次")

        time.sleep(10)

    return None


if __name__ == '__main__':
    print("格式为: OT78EM13W10F02001338 WUH TAO 2024-07-23 CZ5805 E 13:55-15:50")
    zl_str = input("请输入指令(订单号 出发 到达 日期 航班号 舱位 时间):")
    # zl_str = 'OT78EM13W10F02001338 WUH TAO 2024-07-23 CZ5805 E 13:55-15:50'
    # str = 'OB5SUWM1W10H2F006462 CAN TNA 2024-07-02 CZ3663 N 20:55-23:50'
    str_list = zl_str.split(" ")
    order_no = str_list[0]
    dep = str_list[1]
    arr = str_list[2]
    cabin = str_list[5]
    dep_time = f'{str_list[3]} {str_list[6].split("-")[0]}'
    arr_time = f'{str_list[3]} {str_list[6].split("-")[1]}'
    flight_no = str_list[4]
    check_price(order_no, flight_no, dep, arr, cabin, dep_time, arr_time)
